//
//  PatrolTaskTableViewController.m
//  Estate
//
//  Created by wangdongdong on 16/9/9.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "PatrolTaskTableViewController.h"
#import "DefaineCell.h"
#import "SelectConcludeCell.h"
#import "B_wuLiaoCell.h"
#import "TableTopStateCell.h"
#import "ScoureCell.h"
#import "H1_ImagesCell.h"
#import "DoubleBtnCell.h"
#import "PictureViewController.h"

#import "InspectProcessRecordModel.h"
#import "UIActionSheet+Common.h"


@interface PatrolTaskTableViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>

// 附件模型
@property (strong, nonatomic) Tweet *curTweet;
// 图片路径数组
@property (strong, nonatomic) NSMutableArray *selectedAssetURLs;
// 创建时间
@property (copy, nonatomic) NSString *nowTime;
// 检查情况
@property (copy, nonatomic) NSString *caseStr;
// 备注(检查说明)
@property (copy, nonatomic) NSString *note;
// 分数
@property (copy, nonatomic) NSString *grades;
// 当前巡检流程记录model
@property (strong, nonatomic) InspectProcessRecordModel *iPRModel;
// 巡检结论
@property (copy, nonatomic) NSString* conclude;
// 附件表的ID
@property (strong, nonatomic) NSMutableArray *fileIdArr;
// 编辑
@property (assign, nonatomic) BOOL edit;

// 分值上限
@property (copy, nonatomic) NSString *scoreLimit;

@end

@implementation PatrolTaskTableViewController


// 附件表的ID
- (NSMutableArray *)fileIdArr {
    if (!_fileIdArr) {
        _fileIdArr = [NSMutableArray array];
    }
    return _fileIdArr;
}


- (NSMutableArray *)selectedAssetURLs {
    if(!_selectedAssetURLs){
        _selectedAssetURLs=[NSMutableArray array];
    }
    return _selectedAssetURLs;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"检查任务单";
    // 当前时间
    self.nowTime = [LSUtility nowTime];
    
    //附件模型
    _curTweet = [[Tweet alloc] init];
    self.tableView.bounces = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    
    // 获取当前的巡检流程
    self.iPRModel = [self getInspectProcessRecord];
    // 获取附件数据
    [self getAttachment:[LSUtility queryInspectStateId:self.iPRModel.ID state:@"2"]];
    // 获取分值上限
    self.scoreLimit = [LSUtility getInspectScore:self.iPRModel.INSPECT_ITEM_ID];
    [self refresh:nil];
    [self loadViews];
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(refresh:) name:@"RefreshImage_xjy" object:nil];
}


- (void)refresh:(id)sender{
    if(self.selectedAssetURLs != nil){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            self.curTweet.selectedAssetURLs = self.selectedAssetURLs;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:2]] withRowAnimation:UITableViewRowAnimationFade];
            });
        });
    }
}

-(void)loadViews {
    //注册单元格
    [self.tableView registerClass:[SelectConcludeCell class] forCellReuseIdentifier:@"sCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"B_wuLiaoCell" bundle:nil] forCellReuseIdentifier:@"textCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DefaineCell" bundle:nil] forCellReuseIdentifier:@"defaine"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TableTopStateCell" bundle:nil] forCellReuseIdentifier:@"topCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ScoureCell" bundle:nil] forCellReuseIdentifier:@"scoureCell"];
    [self.tableView registerClass:[H1_ImagesCell class] forCellReuseIdentifier:kCellIdentifier_H1_ImagesCell];
    
    // 是否可编辑
    self.edit = [self.iPRModel.INSPECT_ITEM_STATE isEqualToString:@"1"] || (([self.iPRModel.INSPECT_ITEM_STATE isEqualToString:@"2"] || [self.iPRModel.INSPECT_ITEM_STATE isEqualToString:@"5"]) && [self.iPRModel.LOCAL_MODIFY_STATE isEqualToString:@"ADD"]);
    
    if (self.edit) {
        //添加右上方提交按钮
        self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"wancheng"] style:UIBarButtonItemStyleDone target:self action:@selector(clickSave)];
    }
}

// 获取巡检记录详情
- (InspectProcessRecordModel *)getInspectProcessRecord {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    NSString *IPRStr = [NSString stringWithFormat:@"SELECT * FROM INSPECT_PROCESS_RECORD WHERE INSPECT_PROCESS_ID = '%@' AND INSPECT_USER_ID = '%@' AND INSPECT_USER_ITEM_ID = '%@' ORDER BY INSPECT_ITEM_STATE DESC", self.IPID, USERID, self.IUIID];
    FMResultSet *result = [db executeQuery:IPRStr];
    
    InspectProcessRecordModel *iPRModel = [[InspectProcessRecordModel alloc] init];
    while ([result next]) {
        iPRModel.ID = [result stringForColumn:@"ID"];
        iPRModel.INSPECT_USER_ITEM_ID = [result stringForColumn:@"INSPECT_USER_ITEM_ID"];
        iPRModel.PRO_ID = [result stringForColumn:@"PRO_ID"];
        iPRModel.INSPECT_PROCESS_ID = [result stringForColumn:@"INSPECT_PROCESS_ID"];
        iPRModel.INSPECT_USER_ID = [result stringForColumn:@"INSPECT_USER_ID"];
        iPRModel.INSPECT_ITEM_ID = [result stringForColumn:@"INSPECT_ITEM_ID"];
        iPRModel.INSPECT_ITEM_STATE = [result stringForColumn:@"INSPECT_ITEM_STATE"];
        iPRModel.INSPECT_INFO = [result stringForColumn:@"INSPECT_INFO"];
        iPRModel.INSPECT_DESC = [result stringForColumn:@"INSPECT_DESC"];
        iPRModel.INSPECT_RESULT = [result stringForColumn:@"INSPECT_RESULT"];
        iPRModel.INSPECT_SCORE = [result stringForColumn:@"INSPECT_SCORE"];
        iPRModel.INSPECT_ITEM_RECIFICATE_LEADER = [result stringForColumn:@"INSPECT_ITEM_RECIFICATE_LEADER"];
        iPRModel.INSPECT_RECIFICATE_DESC = [result stringForColumn:@"INSPECT_RECIFICATE_DESC"];
        iPRModel.INSPECT_RECIFICATE_REVIEW_USER = [result stringForColumn:@"INSPECT_RECIFICATE_REVIEW_USER"];
        iPRModel.INSPECT_RECIFICATE_REVIRE_SCORE = [result stringForColumn:@"INSPECT_RECIFICATE_REVIRE_SCORE"];
        iPRModel.INSPECT_RECIFICATE_REVIEW = [result stringForColumn:@"INSPECT_RECIFICATE_REVIEW"];
        iPRModel.INSPECT_DO_TIME = [result stringForColumn:@"INSPECT_DO_TIME"];
        iPRModel.EXTEND_INFO = [result stringForColumn:@"EXTEND_INFO"];
        iPRModel.CREATE_TIME = [result stringForColumn:@"CREATE_TIME"];
        iPRModel.CREATE_IP = [result stringForColumn:@"CREATE_IP"];
        iPRModel.MODIFY_USER_NAME = [result stringForColumn:@"MODIFY_USER_NAME"];
        iPRModel.MODIFY_IP = [result stringForColumn:@"MODIFY_IP"];
        iPRModel.MODIFY_TIME = [result stringForColumn:@"MODIFY_TIME"];
        iPRModel.LOCAL_MODIFY_STATE = [result stringForColumn:@"LOCAL_MODIFY_STATE"];
        break;
    }
    [db close];
    return iPRModel;
}


// 获取巡检记录详情
//- (InspectProcessRecordModel *)getInspectProcessRecord:(NSString *)state {
//    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
//    [db open];
//    
//    NSString *IPRStr = [NSString stringWithFormat:@"SELECT * FROM INSPECT_PROCESS_RECORD WHERE INSPECT_PROCESS_ID = '%@' AND INSPECT_USER_ID = '%@' AND INSPECT_USER_ITEM_ID = '%@' AND INSPECT_ITEM_STATE = '%@'", self.IPID, USERID, self.IUIID, state];
//    FMResultSet *result = [db executeQuery:IPRStr];
//    
//    InspectProcessRecordModel *iPRModel = [[InspectProcessRecordModel alloc] init];
//    while ([result next]) {
//        iPRModel.ID = [result stringForColumn:@"ID"];
//        iPRModel.INSPECT_USER_ITEM_ID = [result stringForColumn:@"INSPECT_USER_ITEM_ID"];
//        iPRModel.PRO_ID = [result stringForColumn:@"PRO_ID"];
//        iPRModel.INSPECT_PROCESS_ID = [result stringForColumn:@"INSPECT_PROCESS_ID"];
//        iPRModel.INSPECT_USER_ID = [result stringForColumn:@"INSPECT_USER_ID"];
//        iPRModel.INSPECT_ITEM_ID = [result stringForColumn:@"INSPECT_ITEM_ID"];
//        iPRModel.INSPECT_ITEM_STATE = [result stringForColumn:@"INSPECT_ITEM_STATE"];
//        iPRModel.INSPECT_INFO = [result stringForColumn:@"INSPECT_INFO"];
//        iPRModel.INSPECT_DESC = [result stringForColumn:@"INSPECT_DESC"];
//        iPRModel.INSPECT_RESULT = [result stringForColumn:@"INSPECT_RESULT"];
//        iPRModel.INSPECT_SCORE = [result stringForColumn:@"INSPECT_SCORE"];
//        iPRModel.INSPECT_ITEM_RECIFICATE_LEADER = [result stringForColumn:@"INSPECT_ITEM_RECIFICATE_LEADER"];
//        iPRModel.INSPECT_RECIFICATE_DESC = [result stringForColumn:@"INSPECT_RECIFICATE_DESC"];
//        iPRModel.INSPECT_RECIFICATE_REVIEW_USER = [result stringForColumn:@"INSPECT_RECIFICATE_REVIEW_USER"];
//        iPRModel.INSPECT_RECIFICATE_REVIRE_SCORE = [result stringForColumn:@"INSPECT_RECIFICATE_REVIRE_SCORE"];
//        iPRModel.INSPECT_RECIFICATE_REVIEW = [result stringForColumn:@"INSPECT_RECIFICATE_REVIEW"];
//        iPRModel.INSPECT_DO_TIME = [result stringForColumn:@"INSPECT_DO_TIME"];
//        iPRModel.EXTEND_INFO = [result stringForColumn:@"EXTEND_INFO"];
//        iPRModel.CREATE_TIME = [result stringForColumn:@"CREATE_TIME"];
//        iPRModel.CREATE_IP = [result stringForColumn:@"CREATE_IP"];
//        iPRModel.MODIFY_USER_NAME = [result stringForColumn:@"MODIFY_USER_NAME"];
//        iPRModel.MODIFY_IP = [result stringForColumn:@"MODIFY_IP"];
//        iPRModel.MODIFY_TIME = [result stringForColumn:@"MODIFY_TIME"];
//        iPRModel.LOCAL_MODIFY_STATE = [result stringForColumn:@"LOCAL_MODIFY_STATE"];
//    }
//    [db close];
//    return iPRModel;
//}

// 获取附件数据
- (void)getAttachment:(NSString *)fileId {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    //11.13 更改
    
    NSArray *fileArray=[LSUtility queryAllAttachment:fileId];
    for (NSDictionary *fileDic in fileArray) {
        NSString *fileName=fileDic[@"FILE_NAME"];
        NSString *filePath=[DEF_FILE_PATH stringByAppendingString:
                            [NSString stringWithFormat:@"/%@",fileName]];
        [self.selectedAssetURLs addObject:filePath];
        //添加到需要删除的附件数组
        [self.fileIdArr addObject:fileDic[@"ID"]];
    }
    
//    NSString *sql = [NSString stringWithFormat:@"SELECT FILE_NAME, ID FROM ATTACHMENT WHERE FILE_ID = '%@'", fileId];
//    FMResultSet *result = [db executeQuery:sql];
//    
//    while ([result next]) {
//        
//        // 记录图片名
//        NSString *fileName = [result stringForColumn:@"FILE_NAME"];
//        NSString *filePath = [DEF_FILE_PATH stringByAppendingString:
//                              [NSString stringWithFormat:@"/%@",fileName]];
//        NSString *ID = [result stringForColumn:@"ID"];
//        
//        [self.fileIdArr addObject:ID];
//        [self.selectedAssetURLs addObject:filePath];
//    }
    [db close];
}

#pragma  mrak--UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section==0){
        return 0.001;
    }else{
        return 10;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        return 4;
    }else if (section == 1) {
        if (!self.iPRModel.INSPECT_ITEM_ID || [self.iPRModel.INSPECT_ITEM_ID isEqualToString:@""]) {
            return 5;
        } else {
            return 6;
        }
    } else {
        return 1;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    long section = indexPath.section;
    long row = indexPath.row;
    
    if(section == 0) {
        return 44;
        
    } else if (section == 1){
        if (!self.iPRModel.INSPECT_ITEM_ID || [self.iPRModel.INSPECT_ITEM_ID isEqualToString:@""]) {
            if(row == 0 || row == 1 || row == 3) {
                return 100;
                
            } else {
                return 44;
            }
            
        } else {
            if(row == 1 || row == 2 || row == 4) {
                return 100;
                
            } else {
                return 44;
            }
        }
    } else {
        return  [H1_ImagesCell cellHeightWithObj:_curTweet title:@"附件信息"];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    long section = indexPath.section;
    long row = indexPath.row;
    
    if (section == 0) {
        if (row == 0) {
            TableTopStateCell *cell = [tableView dequeueReusableCellWithIdentifier:@"topCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.title.text = [NSString stringWithFormat: @"%@%@检查任务单", [LSUtility dateNow], DEF_PERSISTENT_GET_OBJECT(@"realname")];
            return cell;
            
        } else if (row == 1) {  // 项目名
            DefaineCell *dCell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
            dCell.selectionStyle=UITableViewCellSelectionStyleNone;
            dCell.title.text = @"项   目:";
            if(self.IPID){
                NSString *proid=[LSUtility getProcessProIdByRecordID: self.iPRModel.ID];
                NSString *proName=[LSUtility getProjectNameByProjectId:proid][@"PROJECT_NAME"];
                dCell.text.text=DEFISNUL(proName);
            }else{
                
                dCell.text.text = DEF_PERSISTENT_GET_OBJECT(@"proname");
            }
            
            return  dCell;
            
        } else if (row == 2) {  // 记录人
            DefaineCell *dCell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
            dCell.selectionStyle=UITableViewCellSelectionStyleNone;
            dCell.title.text = @"记录人:";
            dCell.text.text = DEF_PERSISTENT_GET_OBJECT(@"realname");
            return dCell;
            
        } else {    // 时间
            DefaineCell *dCell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
            dCell.selectionStyle=UITableViewCellSelectionStyleNone;
            dCell.title.text=@"时   间:";
            
            if ([self.iPRModel.INSPECT_ITEM_STATE isEqualToString:@"1"]) {
                dCell.text.text = [LSUtility nowTime];
                
            } else{
                dCell.text.text = self.iPRModel.CREATE_TIME;
            }
            return dCell;
        }
        
    } else if (section==1) {
        
        // 结论
        if (!self.iPRModel.INSPECT_RESULT || [self.iPRModel.INSPECT_RESULT isEqualToString:@""]) {
            self.conclude = self.conclude ? self.conclude : @"1";
            
        } else {
            self.conclude = self.conclude ? self.conclude : self.iPRModel.INSPECT_RESULT;
        }
        
        if (self.iPRModel.INSPECT_ITEM_ID && ![self.iPRModel.INSPECT_ITEM_ID isEqualToString:@""]) {    // 有巡检项ID
            
            if (row == 0) {
                DefaineCell *dCell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
                dCell.selectionStyle=UITableViewCellSelectionStyleNone;
                dCell.title.text = @"检查类:";
                dCell.text.text = self.firstInspectItem;
                return dCell;
                
            } else if (row == 1) {
                B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                cell.isEdit = NO;
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                cell.title.text = @"检查内容:";
                cell.text.text = self.secondInspectItem;
                if (self.edit) {
//                    cell.text.backgroundColor = [UIColor lightGrayColor];
                }
                return cell;
                
            } else if (row == 2) {
                B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                cell.title.text = @"检查情况:";
                cell.text.text = self.caseStr ? self.caseStr : self.iPRModel.INSPECT_INFO;
                self.caseStr = self.caseStr ? self.caseStr : self.iPRModel.INSPECT_INFO;
                
                if (self.edit) {
                    cell.text.placeholder = @"请输入检查情况";
                    cell.textValueChangedBlock = ^(NSString *cStr) {
                        self.caseStr = cStr;
                    };
                } else {
                    cell.isEdit = NO;
                }
                return cell;
                
            } else if (row == 3) {
                if (self.edit) {
                    SelectConcludeCell *cell=[tableView dequeueReusableCellWithIdentifier:@"sCell" forIndexPath:indexPath];
                    cell.lastBtn.selected = NO;
                    cell.title.text = @"结   论:";
                    
                    cell.clickQualifiedBlock = ^ {
                        self.conclude = @"1";
                    };
                    cell.clickUnqualifiedBlock = ^ {
                        self.conclude = @"0";
                    };
                    cell.clickNoRelateBlock = ^ {
                        self.conclude = @"2";
                    };
                    
                    // 设置选中项
                    [cell setBtntype:self.conclude];
                    cell.isEdit = YES;
                    return cell;
                    
                } else {
                    DefaineCell *dCell = [tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
                    dCell.selectionStyle = UITableViewCellSelectionStyleNone;
                    dCell.title.text = @"结   论:";
                    
                    if ([self.iPRModel.INSPECT_RESULT isEqualToString:@"0"]) {
                        dCell.text.text = @"不合格";
                        
                    } else if ([self.iPRModel.INSPECT_RESULT isEqualToString:@"1"]) {
                        dCell.text.text = @"合格";
                        
                    } else if ([self.iPRModel.INSPECT_RESULT isEqualToString:@"2"]) {
                        dCell.text.text = @"不涉及";
                    }
                    return dCell;
                }
            } else if (row == 4) {
                B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                cell.title.text = @"备   注:";
                cell.text.text = self.note ? self.note : self.iPRModel.INSPECT_DESC;
                self.note = self.note ? self.note : self.iPRModel.INSPECT_DESC;
                
                if (self.edit) {
                    cell.text.placeholder = @"请输入备注";
                    cell.textValueChangedBlock = ^(NSString *cStr) {
                        self.note = cStr;
                    };
                } else {
                    cell.isEdit = NO;
                }
                return cell;
                
            } else {
                if (self.edit) {
                    ScoureCell *cell = [tableView dequeueReusableCellWithIdentifier:@"scoureCell" forIndexPath:indexPath];
                    cell.scoreLimit = self.scoreLimit;
                    cell.view = self.navigationController.view;
                    cell.title.text = @"评   分:";
                    cell.title.font = [UIFont systemFontOfSize:17];
                    
                    if (!self.iPRModel.INSPECT_SCORE || [self.iPRModel.INSPECT_SCORE isEqualToString:@""]) {
                        cell.textFile.text = self.grades ? self.grades : self.scoreLimit;
                        
                    } else {
                        cell.textFile.text = self.grades ? self.grades : self.iPRModel.INSPECT_SCORE;
                    }
                    
                    cell.textBlock = ^(NSString *value){
                        self.grades = value;
                        NSLog(@"评分:%@",self.grades);
                    };
                    return cell;
                    
                } else {
                    DefaineCell *dCell = [tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
                    dCell.selectionStyle = UITableViewCellSelectionStyleNone;
                    dCell.title.text = @"评   分:";
                    dCell.text.text = self.iPRModel.INSPECT_SCORE;
                    return dCell;
                }
            }
        } else {    // 无巡检项ID
            
            if (row == 0) {
                B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                cell.isEdit = NO;
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                cell.title.text = @"检查内容:";
                cell.text.text = self.secondInspectItem;
                if (self.edit) {
//                    cell.text.backgroundColor = [UIColor lightGrayColor];
                }
                return cell;
                
            } else if (row == 1) {
                B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                cell.title.text = @"检查情况:";
                cell.text.text = self.caseStr ? self.caseStr : self.iPRModel.INSPECT_INFO;
                self.caseStr = self.caseStr ? self.caseStr : self.iPRModel.INSPECT_INFO;
                
                if (self.edit) {
                    cell.text.placeholder = @"请输入检查情况";
                    cell.textValueChangedBlock = ^(NSString *cStr) {
                        self.caseStr = cStr;
                    };
                } else {
                    cell.isEdit = NO;
                }
                return cell;
                
            } else if (row == 2) {
                if (self.edit) {
                    SelectConcludeCell *cell=[tableView dequeueReusableCellWithIdentifier:@"sCell" forIndexPath:indexPath];
                    cell.isEdit = YES;
                    cell.lastBtn.selected = NO;
                    cell.title.text = @"结   论";
                    
                    cell.clickQualifiedBlock = ^ {
                        self.conclude = @"1";
                    };
                    cell.clickUnqualifiedBlock=^ {
                        self.conclude = @"0";
                    };
                    cell.clickNoRelateBlock=^ {
                        self.conclude = @"2";
                    };
                    // 设置选中项
                    [cell setBtntype:self.conclude];
                    return cell;
                    
                } else {
                    DefaineCell *dCell = [tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
                    dCell.selectionStyle = UITableViewCellSelectionStyleNone;
                    dCell.title.text = @"结   论:";
                    
                    if ([self.iPRModel.INSPECT_RESULT isEqualToString:@"0"]) {
                        dCell.text.text = @"不合格";
                        
                    } else if ([self.iPRModel.INSPECT_RESULT isEqualToString:@"1"]) {
                        dCell.text.text = @"合格";
                        
                    } else if ([self.iPRModel.INSPECT_RESULT isEqualToString:@"2"]) {
                        dCell.text.text = @"不涉及";
                    }
                    return dCell;
                }
            } else if (row == 3) {
                B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                cell.title.text = @"备   注:";
                cell.text.text = self.note ? self.note : self.iPRModel.INSPECT_DESC;
                self.note = self.note ? self.note : self.iPRModel.INSPECT_DESC;
                
                if (self.edit) {
                    cell.text.placeholder = @"请输入备注";
                    cell.textValueChangedBlock = ^(NSString *cStr) {
                        self.note = cStr;
                    };
                } else {
                    cell.isEdit = NO;
                }
                return cell;
                
            } else {
                if (self.edit) {
                    ScoureCell *cell = [tableView dequeueReusableCellWithIdentifier:@"scoureCell" forIndexPath:indexPath];
                    cell.scoreLimit = self.scoreLimit;
                    cell.view = self.navigationController.view;
                    cell.title.text = @"评   分:";
                    cell.title.font = [UIFont systemFontOfSize:17];
                    
                    if (!self.iPRModel.INSPECT_SCORE || [self.iPRModel.INSPECT_SCORE isEqualToString:@""]) {
                        cell.textFile.text = self.grades ? self.grades : self.scoreLimit;
                        
                    } else {
                        cell.textFile.text = self.grades ? self.grades : self.iPRModel.INSPECT_SCORE;
                    }
                    
                    cell.textBlock = ^(NSString *value){
                        self.grades = value;
                        NSLog(@"评分:%@",self.grades);
                    };
                    return cell;
                    
                } else {
                    DefaineCell *dCell = [tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
                    dCell.selectionStyle = UITableViewCellSelectionStyleNone;
                    dCell.title.text = @"评   分:";
                    dCell.text.text = self.iPRModel.INSPECT_SCORE;
                    return dCell;
                }
            }
        }
    } else {    // 图片附件
        WEAKSELF
        H1_ImagesCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_H1_ImagesCell forIndexPath:indexPath];
        if (self.edit) {
            cell.isEdit = YES;
        } else {
            cell.isEdit = NO;
        }
        
        [cell setTitle:@"附件信息"];
        [cell setTitleColor:[UIColor colorWithRed:0.22 green:0.64 blue:0.59 alpha:1.00]];
        cell.curTweet = _curTweet;
        cell.addPicturesBlock = ^(){
            [weakSelf showActionForPhoto];
        };
        cell.deleteTweetImageBlockUrl= ^(TweetImage *toDelete,NSString *deUrl){
            //移除图片
            [weakSelf.curTweet deleteATweetImage:toDelete];
            //移除数组
            [weakSelf.selectedAssetURLs removeObject:deUrl];
            
            [weakSelf refresh:nil];
        };
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        return cell;
    }
}

#pragma mark--保存
- (void)clickSave {
    if (!self.caseStr || [self.caseStr isEqualToString:@""]) {
        [LSUtility showToastWithMessage:@"请填写检查情况" inView:self.navigationController.view Andtime:1.];
    } else {
        // 修改用户巡检项表
        [self modifyInspectUserItem];
        
        if ([self.iPRModel.INSPECT_ITEM_STATE isEqualToString:@"1"]) {
            
            // 新增巡检记录
            [self addFlowRecordData];
            
        } else if ([self.iPRModel.INSPECT_ITEM_STATE isEqualToString:@"2"] || [self.iPRModel.INSPECT_ITEM_STATE isEqualToString:@"5"]) {
            // 先删除附件表中的数据
            [self deleteLastData];
            // 修改巡检记录
            [self modifyInspectRecord];
            // 新增附件表
            [self insertAttachment:self.iPRModel.ID];
        }
        
        // 刷新列表页
        [[NSNotificationCenter defaultCenter] postNotificationName:@"editInspect" object:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

// 删除本地数据
- (void)deleteLocalData:(NSString *)ID {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    NSString *sqlStr = [NSString stringWithFormat:@"DELETE FROM INSPECT_PROCESS_RECORD WHERE ID = '%@'", ID];
    if ([db executeUpdate:sqlStr]) {
        NSLog(@"删除巡检记录成功");
        
    } else {
        NSLog(@"删除巡检记录失败");
    }
    [db close];
}

#pragma mark - 修改用户巡检项表
- (void)modifyInspectUserItem {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    // 巡检状态
    NSString *state;
    if ([self.conclude intValue] == 2) {
        state = @"5";
    } else {
        state = @"2";
    }
    
    NSString *IUISql = [NSString stringWithFormat:@"UPDATE INSPECT_USER_ITEM SET INSPECT_CURRENT_STATE = '%@', INSPECT_DESC = '%@', LOCAL_MODIFY_STATE = 'MOD', MODIFY_USER_NAME = '%@', MODIFY_TIME = '%@', MODIFY_IP = '%@' WHERE ID = '%@'", state, self.note, DEF_PERSISTENT_GET_OBJECT(@"realname"), self.nowTime, [LSUtility getIPAddress], self.IUIID];
    if([db executeUpdate:IUISql]) {
        NSLog(@"修改用户巡检项成功");
    } else {
        NSLog(@"修改用户巡检项失败");
    }
    [db close];
}

#pragma mark - 新增巡检流程记录
- (void)addFlowRecordData {
    NSString *ID = [NSUUID UUID].UUIDString;
    [self insertAttachment:ID];
    
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper = [DBHelper help];
    
    // 分数
    if (!self.grades) {
        self.grades = self.scoreLimit;
    }
    
    // 巡检状态
    NSString *state;
    if ([self.conclude intValue] == 2) {
        state = @"5";
        
    } else {
        state = @"2";
    }
    
    //字段及对应值
    NSDictionary *pragameDic = [NSDictionary dictionary];
    pragameDic = @{
                   @"ID":ID,
                   @"INSPECT_USER_ITEM_ID":DEFISNUL(self.iPRModel.INSPECT_USER_ITEM_ID),
                   @"PRO_ID":DEFISNUL(self.iPRModel.PRO_ID),
                   @"INSPECT_PROCESS_ID":DEFISNUL(self.iPRModel.INSPECT_PROCESS_ID),
                   @"INSPECT_USER_ID":DEFISNUL(self.iPRModel.INSPECT_USER_ID),
                   @"INSPECT_ITEM_ID":DEFISNUL(self.iPRModel.INSPECT_ITEM_ID),
                   @"INSPECT_ITEM_STATE":state,
                   @"INSPECT_INFO":DEFISNUL(self.caseStr),
                   @"INSPECT_DESC":DEFISNUL(self.note),
                   @"INSPECT_RESULT":DEFISNUL(self.conclude),
                   @"INSPECT_SCORE":DEFISNUL(self.grades),
                   @"INSPECT_ITEM_RECIFICATE_LEADER":DEFISNUL(self.iPRModel.INSPECT_ITEM_RECIFICATE_LEADER),
                   @"INSPECT_RECIFICATE_DESC":DEFISNUL(self.iPRModel.INSPECT_RECIFICATE_DESC),
                   @"INSPECT_RECIFICATE_REVIEW_USER":DEFISNUL(self.iPRModel.INSPECT_RECIFICATE_REVIEW_USER),
                   @"INSPECT_RECIFICATE_REVIRE_SCORE":DEFISNUL(self.iPRModel.INSPECT_RECIFICATE_REVIRE_SCORE),
                   @"INSPECT_RECIFICATE_REVIEW":DEFISNUL(self.iPRModel.INSPECT_RECIFICATE_REVIEW),
                   @"INSPECT_DO_TIME":DEFISNUL(self.iPRModel.INSPECT_DO_TIME),
                   @"EXTEND_INFO":DEFISNUL(self.iPRModel.EXTEND_INFO),
                   @"CREATE_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"realname"),
                   @"CREATE_TIME":DEFISNUL(self.nowTime),
                   @"CREATE_IP":[LSUtility getIPAddress],
                   @"MODIFY_USER_NAME":@"",
                   @"MODIFY_IP":[LSUtility getIPAddress],
                   @"MODIFY_TIME":DEFISNUL(self.nowTime),
                   @"LOCAL_MODIFY_USER_NAME":@"",
                   @"LOCAL_MODIFY_TIME":@"",
                   @"LOCAL_MODIFY_STATE":@"ADD",
                   };
    BOOL isAdd = [dbhelper DataBase:db insertKeyValues:pragameDic intoTable:INSPECT_PROCESS_RECORD];
    if (isAdd) {
        NSLog(@"巡检记录添加成功");
    } else {
        NSLog(@"巡检记录添加失败");
    }
}

// 先删除附件表中的数据
-(void)deleteLastData {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    for (int i = 0; i < self.fileIdArr.count; i++) {
        NSString *sql = [NSString stringWithFormat:@"DELETE FROM ATTACHMENT WHERE ID = '%@'",self.fileIdArr[i]];
        
        if ([db executeUpdate:sql]) {
            NSLog(@"删除附件表成功");
        } else {
            NSLog(@"删除附件表失败");
        }
    }
    [db close];
}

#pragma mark - 修改巡检流程记录
- (void)modifyInspectRecord {
    if (!self.grades) {
        self.grades = self.iPRModel.INSPECT_SCORE;
    }
    
    // 巡检状态
    NSString *state;
    if ([self.conclude intValue] == 2) {
        state = @"5";
        
    } else {
        state = @"2";
    }
    
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *iprSql = [NSString stringWithFormat:@"UPDATE INSPECT_PROCESS_RECORD SET INSPECT_ITEM_STATE = '%@', INSPECT_INFO = '%@', INSPECT_RESULT = '%@', INSPECT_DESC = '%@', INSPECT_SCORE = '%@', MODIFY_TIME = '%@', MODIFY_IP = '%@' WHERE ID = '%@'", state, self.caseStr, self.conclude, self.note, self.grades, self.nowTime, [LSUtility getIPAddress], self.iPRModel.ID];
    
    if([db executeUpdate:iprSql]) {
        NSLog(@"修改巡检记录成功");
    } else {
        NSLog(@"修改巡检记录失败");
    }
    [db close];
}

#pragma mark - 新增附件表
- (NSArray *)insertAttachment:(NSString *)recordIds {
    NSArray *rFileArr;
    if (self.selectedAssetURLs.count > 0) {
        rFileArr = [LSUtility insertAttachmentFromArray:self.selectedAssetURLs andRecordId:recordIds andType:@"INSPECT_01" andRecifyState:@"0"];
    }
    return rFileArr;
}

// 将字典或者数组转化为JSON串
- (NSString *)toJSONData:(id)theData{
    NSString *jsonString = nil;
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData
                                                       options:0
                                                         error:&error];
    
    if ([jsonData length] != 0 && error == nil){
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }else{
        NSLog(@"转JSON失败%@", error);
    }
    return jsonString;
}

/*
 *点击方法
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

/*
 *  此方法让cell横线置顶
 */
-(void)viewDidLayoutSubviews {
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}

#pragma mark UIActionSheet M

- (void)showActionForPhoto{
    [self.view endEditing:YES];
    //    @weakify(self);
    [[UIActionSheet bk_actionSheetCustomWithTitle:nil buttonTitles:@[@"拍照", @"从相册选择"] destructiveTitle:nil cancelTitle:@"取消" andDidDismissBlock:^(UIActionSheet *sheet, NSInteger index) {
        
        [self photoActionSheet:sheet DismissWithButtonIndex:index];
        
    }] showInView:self.view];
}

- (void)photoActionSheet:(UIActionSheet *)sheet DismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        //拍照
        if (self.curTweet.tweetImages.count >= 9) {//照片最多这么多
            kTipAlert(@"最多只可选择9张照片，已经选满了。先去掉一张照片再拍照呗～");
            return;
        }
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = NO;//设置可编辑
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];//进入照相界面
    }else if (buttonIndex == 1){
        PictureViewController *picCtr=[[PictureViewController alloc]init];
        picCtr.flag=@"file";
        NSMutableArray *array = [self.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
        picCtr.selectedImages=[[NSMutableArray alloc] initWithArray:array];
        picCtr.selectedImageBlock = ^(NSMutableArray *array) {
//            for (NSString *path in array) {
//                //添加图片路径到已选数组
//                [self.selectedAssetURLs addObject:path];
//            }
            self.selectedAssetURLs = array;
        };
        [self.navigationController pushViewController:picCtr animated:YES];
    }
}

#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    self.curTweet.editImageView = [[EditImageView alloc]initWithImage:image];
    WEAKSELF
    self.curTweet.editImageView.completeBlock = ^(NSString *path) {
        [weakSelf.curTweet addASelectedAssetURL:path];
        [weakSelf.selectedAssetURLs addObject:path];
        [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:2]] withRowAnimation:UITableViewRowAnimationFade];
    };
    [picker dismissViewControllerAnimated:YES completion:nil];
 }

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == self.tableView) {
        [self.view endEditing:YES];
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"RefreshImage_xjy" object:nil];
}

@end



